package com.tanhua.dubbo.api;

import cn.hutool.core.util.PageUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class VideoApiImpl implements VideoApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    //视频上传
    @Override
    public void save(Video video) {
        mongoTemplate.save(video);
    }

    //根据id集合查询
    @Override
    public List<Video> findByIds(String[] ids, Integer page, Integer pagesize) {
        //redis中支持最大查询条数
        int totalPage = PageUtil.totalPage(ids.length, pagesize);
        if (page <= totalPage) {
            Criteria criteria = Criteria.where("id").in(ids);
            Query query = Query.query(criteria)
                    .skip((page - 1) * pagesize)
                    .limit(pagesize);
            return mongoTemplate.find(query, Video.class);
        } else {
            //查询所有
            return findAll(page - totalPage, pagesize);
        }
    }

    //查询所有
    @Override
    public List<Video> findAll(Integer page, Integer pagesize) {
        Query query = new Query().with(Sort.by(Sort.Order.desc("created")))
                .skip((page - 1) * pagesize)
                .limit(pagesize);
        return mongoTemplate.find(query, Video.class);
    }

    //根据用户id进行分页查询
    @Override
    public PageResult findByUserId(Long uid, Integer page, Integer pagesize) {
        Criteria criteria = Criteria.where("userId").is(uid);
        Query query = Query.query(criteria);
        //查询总数
        long count = mongoTemplate.count(query, Video.class);
        query.with(Sort.by(Sort.Order.desc("created")))
                .limit(pagesize)
                .skip((page - 1) * pagesize);
        List<Video> videos = mongoTemplate.find(query, Video.class);
        return new PageResult(page,pagesize,count,videos);
    }

    @Override
    public List<Video> findByUid(Long uid) {
        Criteria criteria = Criteria.where("userId").is(uid);
        Query query = Query.query(criteria);
        return   mongoTemplate.find(query,Video.class);
    }

    //    //更新
//    @Override
//    public void updateById(String uid) {
//        Criteria criteria = Criteria.where("userId").is(uid);
//        Query query = Query.query(criteria);
//        Video video = mongoTemplate.findOne(query, Video.class);
//        video.setLoveCount(video.getLoveCount() + 1);
//        mongoTemplate.save(video);
//    }
}
